
//JS事件委托
window.onload = function(){
	var oChess = document.getElementById('chessBoard');
	var isWin = false;
	var lab = document.getElementById('lab');
	lab.onclick = function(){
		console.log(document.getElementById('toggle').checked);
		
		if(document.getElementById('toggle').checked){
			alert("那就再来一次吧！");
			location.reload();

		}else{
			if(confirm("汪大头！约吗?")){
				alert("嗒哒～");
			}else{
				alert("切～");
				window.close();
			}
		}
		
	}

	oChess.addEventListener('click',function(ev){
		if(ev.target.style.background.indexOf('images')>0){
			alert("此处已落棋！");
			return false;
		}

		chess.call(ev.target);

	},false)

	var tds = document.getElementsByTagName("td");


	function addClass(obj, cls) {
        obj.className += " " + cls;
    }

    function hasClass(ele,cls) { 
		return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)')); 
	} 

	function removeClass(ele,cls) { 
		if (hasClass(ele,cls)) { 
			var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)'); 
			ele.className=ele.className.replace(reg,' '); 
		} 
	} 

	//负责下棋

	var chess = function(){
		var color = cnt();

		if(isWin){
			alert("胜负已分，即将刷新页面以重新开局！");
			location.reload();
		}
		this.style.background = 'url(images/'+color+'.png) no-repeat';
		this.style.backgroundSize = '100%';
		var curr = {x:this.cellIndex, y:this.parentElement.rowIndex, color:color};
		judge.call(this,color);
	}


	//判断胜负

	var judge = function(color){
		//找出当前子的横纵位置
		var curr = {x:this.cellIndex, y:this.parentElement.rowIndex, color:color};
		var line = ['','','',''];

		for(var i = 0, tmp = {}; i < 400; i++){
			tmp = {x:tds[i].cellIndex, y:tds[i].parentElement.rowIndex, color:"0"}; 
			if(tds[i].style.background.indexOf('black')>0){
				tmp.color = 'b';
			}else if(tds[i].style.background.indexOf('white')>0){
				tmp.color = 'w';
			}

			if(curr.y == tmp.y){
				line[0] += tmp.color;
			}
			if(curr.x == tmp.x){
				line[1] += tmp.color;
			}
			if((curr.x + curr.y) == (tmp.x + tmp.y)){
				line[2] += tmp.color;
			}
			if((curr.x - tmp.x) == (curr.y - tmp.y)){
				line[3] += tmp.color;
			}
		}
		console.log(line);
		//判断目前子四个方向是否有5个同色子
		color = color == 'black'?'bbbbb':'wwwww';
		for(var i = 0; i < 4; i++){
			if(line[i].indexOf(color)>=0){
				if(color == 'wwwww'){
					console.log(line[i]);
					alert("白棋胜！");
					addClass(lab,'active');
					document.getElementById("chessBox").style.display = "none";
				}else if(color == 'bbbbb'){
					alert("黑棋胜！");
				}
				isWin = true;
				break;
			}
		}
	}

	//闭包黑白落子子判断
	var cnt = (function(){
		var color = 'white';
		return function(){
			if(color == 'black'){
				color = 'white';
			}else{
				color = 'black';
			}
			return color;
		};	
	})();
}


